package cc.rengu.redp.bizimpl.csmc.service.impl;

import cc.rengu.redp.bizimpl.csmc.domain.CClearPlanMap;
import cc.rengu.redp.bizimpl.csmc.domain.CRoleAcctInfo;
import cc.rengu.redp.bizimpl.csmc.dao.CRoleAcctInfoMapper;
import cc.rengu.redp.bizimpl.csmc.service.ICRoleAcctInfoService;
import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.BTermBrandInfo;
import cc.rengu.redp.bizimpl.upmp.domain.BizTmp;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author lizk
 */
@Service
@DS("csmc")
public class CRoleAcctInfoServiceImpl extends ServiceImpl<CRoleAcctInfoMapper, CRoleAcctInfo> implements ICRoleAcctInfoService {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;
    @Autowired
    private IUpmpSysSeqService sysSeqService;

    private long oprMenuId = 1;
    private String oprMenuName = "清分清算管理:角色/账户配置管理";
    private long chkMenuId = 2;
    private String chkMenuName = "清分清算管理:角色/账户配置管理";
    private String webNextUrl = "/admin/csmc/cRoleAcctInfo/edit";

    @Override
    public IPage<CRoleAcctInfo> findByPage(QueryRequest queryRequest, CRoleAcctInfo roleAcctInfo) {
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

        try {
            String instId = roleAcctInfo.getInstId();
            if (Common.isBlank(instId)) {
                instId = user.getInstId();
            }
            LambdaQueryWrapper<CRoleAcctInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(instId)) {
                queryWrapper.eq(CRoleAcctInfo::getInstId, instId);
            }
            if (!StringUtils.isEmpty(roleAcctInfo.getSettleAcctId())) {
                queryWrapper.like(CRoleAcctInfo::getSettleAcctId, roleAcctInfo.getSettleAcctId());
            }
            if(!StringUtils.isEmpty(roleAcctInfo.getRoleId())){
                queryWrapper.like(CRoleAcctInfo::getRoleId,roleAcctInfo.getRoleId());
            }
            queryWrapper.orderByDesc(CRoleAcctInfo::getCreateTime);
            Page<CRoleAcctInfo> page = new Page<>();
            SortUtil.handlePageSort(queryRequest, page, true);
            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("获取角色账户配置管理信息失败", e);
            return null;
        }
    }

    @Override
    public void createRoleAcctInfo(CRoleAcctInfo roleAcctInfo) throws RedpException {
        saveData(roleAcctInfo);
    }

    @Override
    public void updateRoleAcctInfo(CRoleAcctInfo roleAcctInfo) throws RedpException {
        saveData(roleAcctInfo);
    }

    @Override
    public Map<String, Object> cRoleAcctInfoSelect2List(String q, QueryRequest request) {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        if (null == q) {
            return null;
        }
        q = q.replaceAll("&amp;", "&");

        String brandCodeOrName = "";
        String[] param = q.split("&");
        if (null != param && param.length > 0) {
            brandCodeOrName = param[0];
        }
        String instId = "";
        if (null != param && param.length > 1) {
            if (Common.isNotBlank(param[1])) {
                instId = param[1];
            }
        }
        String s = param[2];

        if (org.apache.commons.lang3.StringUtils.isBlank(instId)) {
            instId = user.getInstId();
        }
        try {
            LambdaQueryWrapper<CRoleAcctInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CRoleAcctInfo::getOprStatus, "01");
            queryWrapper.eq(CRoleAcctInfo::getInstId, instId);
            if (s.equals("payerAcctInfo")) {
                queryWrapper.in(CRoleAcctInfo::getSettleAcctId, new String[]{"MOMP_SUBJECT", "COLLECTION_SUBJECT",
                        "DZ_SUBJECT", "UPQC_PAYCHNL_SUBJECT", "UPAC_PAYCHNL_SUBJECT", "NCQS_PAYCHNL_SUBJECT", "CUPS_PAYCHNL_SUBJECT",
                        "BANK_PAYCHNL_SUBJECT", "WCHT_PAYCHNL_SUBJECT", "ALIPAY_PAYCHNL_SUBJECT",
                        "UPGW_PAYCHNL_SUBJECT"});

            } else {
                queryWrapper.eq(CRoleAcctInfo::getSettleAcctId, "ABNFUNDGZ_SUBJECT");
            }
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(brandCodeOrName)) {
                String finalbrandCodeOrName = brandCodeOrName;
                queryWrapper.and(qw -> qw.likeRight(CRoleAcctInfo::getSettleAcctId, finalbrandCodeOrName).or().likeRight(CRoleAcctInfo::getSettleAcctDesc, finalbrandCodeOrName));
            }
            queryWrapper.orderByDesc(CRoleAcctInfo::getCreateTime);
            Page<CRoleAcctInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            Page<CRoleAcctInfo> page1 = this.page(page, queryWrapper);
            List<CRoleAcctInfo> listx = page1.getRecords();
            Map<String, Object> maps = new HashMap<String, Object>();
            Map<String, String> map = new HashMap<String, String>();
            List<Object> list = new ArrayList<Object>();
            if (listx != null) {
                for (int i = 0; i < listx.size(); i++) {
                    CRoleAcctInfo org = listx.get(i);
                    map = new HashMap<String, String>();
                    map.put("id", org.getActualAcct());
                    map.put("name", org.getSettleAcctDesc());

                    list.add(map);
                }
                maps.put("results", list);
                maps.put("total", page.getTotal());
                int pageIndex = Common.isBlank(request.getPageNum()) ? 1 : request.getPageNum();
                if (pageIndex == page1.getTotal()) {
                    maps.put("more", false);
                } else {
                    maps.put("more", true);
                }
            }
            return maps;

        } catch (Exception e) {
            log.error("获取账户信息失败", e);
            return null;
        }
    }

    private void saveData(CRoleAcctInfo entity) throws RedpException {

        String optFlag = entity.getOptFlag();

        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "roleAcctInfo:add");

            entity.setId(null);
            entity.setOprId(user.getOprId());
            entity.setCreateTime(lastUpddt);
            //
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                entity.setOprStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                this.save(entity);
                bizTmpService.saveBizTmp(entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        entity.getOprStatus(), entity.getAuditStatus(), entity.getId(), webNextUrl, null, null, null);

            } else {

                entity.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                this.save(entity);

                bizHisService.saveBizHisNew(entity, entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        entity.getId(), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)) {


            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "roleAcctInfo:edit");


            CRoleAcctInfo dbcroleacctinfo = baseMapper.selectById(id);
            CRoleAcctInfo croleacctinfo = new CRoleAcctInfo();
            CRoleAcctInfo croleacctinfoTmp = new CRoleAcctInfo();
            BeanUtils.copyProperties(dbcroleacctinfo, croleacctinfo);
            BeanUtils.copyProperties(dbcroleacctinfo, croleacctinfoTmp);

            entity.setAuditOprId(user.getId());
            entity.setUpdateTime(lastUpddt);
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                this.saveOrUpdate(croleacctinfo);
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                BeanUtils.copyProperties(entity, croleacctinfoTmp);

                //检查临时表是否有数据，如果没用则新增
                bizTmpService.saveBizTmp(croleacctinfoTmp, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        croleacctinfo.getOprStatus(), croleacctinfo.getAuditStatus(), croleacctinfo.getId(), webNextUrl, null, null, null);

            } else {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                BeanUtils.copyProperties(entity, croleacctinfo);
                this.saveOrUpdate(croleacctinfo);

                //历史表新增
                bizHisService.saveBizHisNew(croleacctinfo, dbcroleacctinfo, user, user.getInstId(),
                        BizOprEnum.OPR_UPDATE.getType(), lastUpddt, String.valueOf(oprMenuId), oprMenuName,
                        croleacctinfo.getId(), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {
            String id = entity.getId();

            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }

            CRoleAcctInfo croleacctinfodb = baseMapper.selectById(id);
            CRoleAcctInfo croleacctinfo = new CRoleAcctInfo();
            BeanUtils.copyProperties(croleacctinfodb, croleacctinfo);

            if (Common.isBlank(croleacctinfo)) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }

            UpmpPrivilegeCheck privilegeCheck = new UpmpPrivilegeCheck();
            String bizOpr = "";
            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag)) {//停用
                String stopReason = entity.getStopReason();

                bizOpr = BizOprEnum.OPR_STOP.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "roleAcctInfo:stop");

                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {

                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType());
                    croleacctinfo.setStopReason(stopReason);

                } else {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    croleacctinfo.setOprStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                    croleacctinfo.setStopReason(stopReason);
                }
            } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag)) {//启用

                bizOpr = BizOprEnum.OPR_USE.getType();

                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "roleAcctInfo:use");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType());
                } else {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    croleacctinfo.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {//注销

                String cancelReason = entity.getCancelReason();
                bizOpr = BizOprEnum.OPR_CANCEL.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "roleAcctInfo:cancel");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());
                    croleacctinfo.setCancelReason(cancelReason);
                } else {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    croleacctinfo.setOprStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
                    croleacctinfo.setCancelReason(cancelReason);
                }
            }
            croleacctinfo.setAuditOprId(user.getId());
            croleacctinfo.setUpdateTime(lastUpddt);
            this.saveOrUpdate(croleacctinfo);

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //检查临时表是否有数据，如果没用则新增
                bizTmpService.saveBizTmp(croleacctinfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        croleacctinfo.getOprStatus(), croleacctinfo.getAuditStatus(), croleacctinfo.getId(), webNextUrl, null, null, null);

            } else {
                //历史表新增
                bizHisService.saveBizHisNew(croleacctinfo, croleacctinfodb, user, user.getInstId(),
                        BizOprEnum.OPR_UPDATE.getType(), lastUpddt, String.valueOf(oprMenuId), oprMenuName,
                        croleacctinfo.getId(), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {

            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }

            //获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getBizTmpDetail(id);
            if (Common.isBlank(tmp)) {
                log.error("根据id没有找到指定临时表数据！");
                throw new RedpException("根据id没有找到指定临时表数据！");
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }
            CRoleAcctInfo cRoleAcctInfoNew = JSON.parseObject(bizdata, CRoleAcctInfo.class);

            CRoleAcctInfo croleacctinfo = baseMapper.selectById(id);
            CRoleAcctInfo croleacctinfold = new CRoleAcctInfo();
            BeanUtils.copyProperties(croleacctinfo, croleacctinfold);

            if (Common.isBlank(croleacctinfo) && !BizOprEnum.OPR_ADD.equals(tmp.getBizOpr())) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }

            String opt = entity.getOpt();
            if (Common.isBlank(opt)) {
                log.error("请求参数(opt)异常!");
                throw new RedpException("请求参数(opt)异常!");
            }

            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                // 审批通过将临时表数据更新到正式表
                BeanUtils.copyProperties(cRoleAcctInfoNew, croleacctinfo);
            } else {
                String approvalRefuseReason = entity.getAuditRefuseReason();
                croleacctinfo.setAuditRefuseReason(approvalRefuseReason);
            }

            String bizOpr = "";
            if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(croleacctinfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                    croleacctinfo.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());

                }
                bizOpr = BizOprEnum.OPR_ADD.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType().equals(croleacctinfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    croleacctinfo.setOprStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
                } else {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_CANCEL.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType().equals(croleacctinfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    croleacctinfo.setOprStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                } else {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_STOP.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType().equals(croleacctinfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    croleacctinfo.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_USE.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(croleacctinfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                    croleacctinfo.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    croleacctinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            }
            this.saveOrUpdate(croleacctinfo);
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                //审批通过将正式表更新到历史表
                bizHisService.saveBizHisNew(croleacctinfo, croleacctinfold, user, user.getInstId(),
                        BizOprEnum.OPR_UPDATE.getType(), lastUpddt, String.valueOf(oprMenuId), oprMenuName,
                        croleacctinfo.getId(), null, null, null);

            }
            // 修改临时表的审核状态等字段
            bizTmpService.saveBizTmp(croleacctinfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                    String.valueOf(oprMenuId), oprMenuName, croleacctinfo.getOprStatus(), croleacctinfo.getAuditStatus(),
                    croleacctinfo.getId(), webNextUrl, null, null, null);

        }

    }
}
